import request from '@/utils/request'
import useUserStore from '@/store/modules/user'

// 查询历史会话列表
export function listSessions(query) {
  return request({
    url: '/system/sessions/list',
    method: 'get',
    params: query
  })
}

// 查询历史会话详细
export function getSessions(id) {
  return request({
    url: '/system/sessions/' + id,
    method: 'get'
  })
}

// 新增历史会话
export function addSessions(data) {
  return request({
    url: '/system/sessions',
    method: 'post',
    data: data
  })
}

// 修改历史会话
export function updateSessions(data) {
  return request({
    url: '/system/sessions',
    method: 'put',
    data: data
  })
}

// 删除历史会话
export function delSessions(id) {
  return request({
    url: '/system/sessions/' + id,
    method: 'delete'
  })
}

// 获取当前会话的对话记录
export function getDialogsBySessionId(sessionId) {
  const userStore = useUserStore()
  return request({
    url: '/system/aiChat/listBySessionId/' + sessionId,
    method: 'get'
  }).then(response => {
    // 获取当前登录用户ID
    const userId = userStore.id;
    console.log("获取会话记录 - sessionId:", sessionId, "userId:", userId);
    
    // 处理返回的数据，标记是否为用户消息
    if (response.data) {
      console.log("原始对话记录数据:", response.data);
      response.data = response.data.map(item => ({
        ...item,
        isUser: String(item.userName) === String(userId)
      }));
      console.log("处理后的对话记录数据:", response.data);
    } else {
      console.log("未获取到对话记录数据");
      response.data = []; // 确保返回空数组而不是 null
    }
    return response;
  }).catch(error => {
    console.error("获取对话记录失败:", error);
    return { data: [] }; // 发生错误时也返回空数组
  });
}
